<?php
namespace app\admin\controller;

\think\Loader::import('controller/Controller', \think\Config::get('traits_path') , EXT);

use app\admin\Controller;
use think\Config;
use think\Db;
use think\Request;
use think\Validate;

class HotelReservation extends Controller
{
    use \app\admin\traits\controller\Controller;
    // 方法黑名单
    protected static $blacklist = [];



    /**
     * 首页
     */
    public function index()
    {
        $data = input();
        // 查询条件
        if ($data['room_type_id']){
            $room_type_id = Db::name('reservation_room')->where('room_type_id',$data['room_type_id'])->field('booking_hotel_id')->select();
//            dump($room_type_id);
            if ($room_type_id){
                $roomTypeId = '';
                foreach ($room_type_id as $index => $item) {
                    $roomTypeId .= $item['booking_hotel_id'].',';
                }
                $roomTypeId = rtrim($roomTypeId,',');
                $map['id'] = ['in', $roomTypeId];
            }
        }
        if ($data['hotel_id']){
            // 从酒店获取酒店id
            $hotelIds = Db::name('hotel')->where('hotel_name','like',"%{$data['hotel_id']}%")->field('id')->select();
            if ($hotelIds) {
                $hotel_id = '';
                foreach ($hotelIds as $index => $hotelId) {
                    $hotel_id .= $hotelId['id'] . ',';

                }
                $hotel_id = rtrim($hotel_id, ',');
                }
                    $map['hotel_id'] = ['in',$hotel_id];
            }

        if ($data['hotel_location']){
            $map['hotel_location'] = ['like',"%{$data['hotel_location']}%"];
        }

        if ($data['hotel_manager']){
            $map['hotel_manager'] = ['like',"%{$data['hotel_manager']}%"];
        }

        if ($data['phone']){
            $map['phone'] = ['like',"%{$data['phone']}%"];
        }

        if ($data['start_time']){
            $start_time = "{$data['start_time']} 0:0:0";
            $end_time = "{$data['start_time']} 23:59:59";
            $map['start_time'] = ['between',[strtotime($start_time),strtotime($end_time)]];
        }
        if ($data['end_time']){
            $start_time = "{$data['end_time']} 0:0:0";
            $end_time = "{$data['end_time']} 23:59:59";
            $map['end_time'] = ['between',[strtotime($start_time),strtotime($end_time)]];
        }
        if ($data['remark']){
            $map['remark'] = ['like',"%{$data['remark']}%"];
        }
        if ($data['create_time']){
            $start_time = "{$data['create_time']} 0:0:0";
            $end_time = "{$data['create_time']} 23:59:59";
            $map['create_time'] = ['between',[strtotime($start_time),strtotime($end_time)]];
        }
        // 查询所有
        // 查询所有
        $map['isdelete'] = 0;
        $listRows = $this->request->param('numPerPage') ?20: Config::get("paginate.list_rows");
        $list = Db::name('hotel_reservation')->where($map)->order('id','desc')->paginate($listRows, false, ['query' => $this->request->get()]);
        $listData = $list->toArray()['data'];
        if ($listData){
            foreach ($listData as $index => $listDatum) {
                $listData[$index]['room_data'] = self::getReservationRoom($listDatum);
            }
        }
        $hotel_room_type = Db::name('hotel_room_type')->where('isdelete',0)->select();
        $count = $list->count();
        $this->view->assign('list',$list);
        $this->view->assign('page',$list->render());
        $this->view->assign('searchCondition',$data);
        $this->view->assign('listData', $listData);
        $this->view->assign('count',$count);
        $this->view->assign('hotel_room_type',$hotel_room_type);
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add(Request $request)
    {
        if ($request->isPost()){
            $postData = $request->post();//获取数据
            // 验证数据
            $rule = [
                'hotel_id'=>'require',
                'end_time'=>'require',
                'start_time'=>'require',
            ];
            $message = [
                'hotel_id.require' => '酒店名称不能为空',
                'end_time.require' => '结束时间不能为空',
                'start_time.require' => '开始时间不能为空',
            ];
            $validate = new Validate($rule,$message);
            $result = $validate->check($postData);
            if (!$result){
                return ajax_return_adv_error($validate->getError());
            }
            unset($postData['id']);
            $hotels = Db::name('hotel')->where('id',$postData['hotel_id'])->select();
            if ($hotels){
                foreach ($hotels as $index => $listDatum) {
                    $postData['hotel_location'] = $listDatum['hotel_location'];
                    $postData['hotel_manager'] = $listDatum['hotel_manager'];
                    $postData['phone'] = $listDatum['phone'];
                }
            }
            $postData['create_time'] = time();
            if (!empty($postData['start_time']) && !empty($postData['end_time']) && ($postData['start_time'] > $postData['end_time'])){
                return ajax_return_adv_error('订单的开始日期不能大于结束日期');
            }

            // 开始日期与结算日期
            $tian = round((strtotime($postData['end_time'])-strtotime($postData['start_time']))/3600/24);
            // 把入住日期与退房日期的相差天数
            $date = [$postData['start_time']];
            for ($i=1; $i<= $tian; $i++){
                array_push($date,date("Y-m-d",strtotime("+{$i} day", strtotime($postData['start_time']))));//添加的
            }

            foreach ($date as $index => $item) {
                $map['start_time'] = ['<=',strtotime($item)];
                $map['end_time'] = ['>=',strtotime($item)];
                $find =  Db::name('hotel_reservation')->where('hotel_id',$postData['hotel_id'])
                    ->where($map)->find();
                if ($find){
                    $hotelName = Db::name('hotel')->where('id',$postData['hotel_id'])->value('hotel_name');
                    return ajax_return_adv_error("酒店名称为:{$hotelName},已存在{$item}的预订房型量!");
                }
            }
            //把日期转换为时间戳
            $postData['start_time']=strtotime($postData['start_time']);
            $postData['end_time']=strtotime($postData['end_time']);
            //判断房型是否重复
            if(is_array($postData['reservation']['room_type_id'])){
                foreach ($postData['reservation']['room_type_id'] as $key=>$vle){
                    $contrast =$postData['reservation']['room_type_id'][$key];
                    $contrasts[]=$contrast;
                }
            }
            $contrastsNumber = array_count_values ($contrasts);
            if($contrastsNumber){
                foreach ($contrastsNumber as $value){
                    if($value>1){
                        return ajax_return_error("房型不能重复！");
                    }
                }
            }
            //存入数据
            $addId = Db::name('hotel_reservation')->insertGetId($postData);
            $reservations=[];

            if(is_array($postData['reservation']['room_type_id'])){
                foreach ($postData['reservation']['room_type_id'] as $key=>$vle){
                    $reservation['room_type_id']=$postData['reservation']['room_type_id'][$key];
                    $reservation['number_of_rooms']=$postData['reservation']['number_of_rooms'][$key];
                    $reservation['hotel_id']=$postData['hotel_id'];
                    $reservation['create_time']=$postData['create_time'];
                    $reservation['booking_hotel_id']=$addId;
                    $reservations[]=$reservation;
                }
            }
            if ($addId){
                if($reservations){
                    $re=Db::name('reservation_room')->insertAll($reservations);
                }
                if($re){
                    return ajax_return_adv("添加成功");
                }
            }else{
                return ajax_return_error("添加失败");
            }
        }else{
            // 查询所有的酒店
            $hotel = Db::name('hotel')->where('isdelete', 0)->select();
            $hotel_room_type = Db::name('hotel_room_type')->where('isdelete',0)->select();
            $this->view->assign('hotel',$hotel);
            $this->view->assign('hotel_room_type',$hotel_room_type);
            return $this->view->fetch('add');
        }
    }

    /**
     * 编辑
     */
    public function edit(Request $request)
    {
        if ($request->isPost()){
            $postData = $request->post();//获取数据

            // 验证数据
            $rule = [
                'hotel_id'=>'require',
                'end_time'=>'require',
                'start_time'=>'require',
            ];
            $message = [
                'hotel_id.require' => '酒店名称不能为空',
                'end_time.require' => '结束时间不能为空',
                'start_time.require' => '开始时间不能为空',
            ];
            $validate = new Validate($rule,$message);
            $result = $validate->check($postData);
            if (!$result){
                return ajax_return_adv_error($validate->getError());
            }
            //判断条件
            $postData['create_time'] = time();
            if (!empty($postData['start_time']) && !empty($postData['end_time']) && ($postData['start_time'] > $postData['end_time'])){
                return ajax_return_adv_error('订单的开始日期不能大于结束日期');
            }
            //判断房型是否重复
            if(is_array($postData['reservation']['room_type_id'])){
                foreach ($postData['reservation']['room_type_id'] as $key=>$vle){
                    $contrast =$postData['reservation']['room_type_id'][$key];
                    $contrasts[]=$contrast;
                }
            }
            $contrastsNumber = array_count_values ($contrasts);
            if($contrastsNumber){
                foreach ($contrastsNumber as $value){
                    if($value>1){
                        return ajax_return_error("房型不能重复！");
                    }
                }
            }

//            // 开始日期与结算日期
//            $tian = round((strtotime($postData['end_time'])-strtotime($postData['start_time']))/3600/24);
//            // 把入住日期与退房日期的相差天数
//            $date = [$postData['start_time']];
//            for ($i=1; $i<= $tian; $i++){
//                array_push($date,date("Y-m-d",strtotime("+{$i} day", strtotime($postData['start_time']))));//添加的
//            }
//
//            foreach ($date as $index => $item) {
//                $map['start_time'] = ['<=',strtotime($item)];
//                $map['end_time'] = ['>=',strtotime($item)];
//                $find =  Db::name('hotel_reservation')->where('hotel_id',$postData['hotel_id'])
//                    ->where($map)->find();
//                if ($find){
//                    $hotelName = Db::name('hotel')->where('id',$postData['hotel_id'])->value('hotel_name');
//                    return ajax_return_adv_error("酒店名称为:{$hotelName},已存在{$item}的预订房型量!");
//                }
//            }
            //把日期转换为时间戳
            $postData['start_time']=strtotime($postData['start_time']);
            $postData['end_time']=strtotime($postData['end_time']);

            //更新数据库
            $update = Db::name('hotel_reservation')->update($postData);
            $reservations=[];


            if(is_array($postData['reservation']['room_type_id'])){
                foreach ($postData['reservation']['room_type_id'] as $key=>$vle){
                    $reservation['id']=$postData['reservation']['id'][$key];
                    $reservation['room_type_id']=$postData['reservation']['room_type_id'][$key];
                    $reservation['number_of_rooms']=$postData['reservation']['number_of_rooms'][$key];
                    $reservation['hotel_id']=$postData['hotel_id'];
                    $reservation['create_time']=$postData['create_time'];
                    $reservation['booking_hotel_id']=$postData['id'];
                    $reservations[]=$reservation;
                }
            }

            //获取更新前数据库的预订房量
            $reservations_id = Db::name("reservation_room")->where('booking_hotel_id',$postData['id'])->select();

            //添加部分
            $add_reservations=[];
            foreach ($reservations as $value){
                if(!$value['id']){
                    $add_reservation=$value;
                    $add_reservations[]=$add_reservation;

                }
            }
            if($add_reservations){

                Db::name('reservation_room')->insertAll($add_reservations);
            }
            //更改部分
            $update_reservations=[];
            foreach ($reservations as $value){
                if($value['id']){
                    $update_reservation=$value;
                    $update_reservations[]=$update_reservation;
                }
            }
            foreach ($update_reservations as $update_reservation){
                $_reservation_id=$update_reservation['id'];
                unset($update_reservation['id']);
                Db::name('reservation_room')->where('id',$_reservation_id)->update($update_reservation);
            }

            //删除部分
            $update_reservation_ids=[];
            foreach ($reservations as $value){
                if($value['id']){
                    $update_reservation_ids[]=$value['id'];
                }
            }
            $delete_reservation_ids=[];
            foreach ( $reservations_id as $value){
                if(!in_array($value['id'],$update_reservation_ids)){
                    $delete_reservation_ids[]=$value['id'];
                }
            }
            $del_map['id']=array('in',$delete_reservation_ids);
            Db::name('reservation_room')->where($del_map)->delete();

            return ajax_return_adv("修改成功");
        }else{
            $data = input();
            if (!$data['id']) {
                return ajax_return_adv_error('缺少参数');
            }
            // 查找该预订酒店信息
            $vo = Db::name('hotel_reservation')->where('id',$data['id'])->find();
            // 查找该酒店的所有房型
            $reservationRoom = Db::name('reservation_room')->where('booking_hotel_id',$vo['id'])->select();

            // 根据酒店的id获取房型
            $room_type = Db::name('room_hotel_number')->where('hotel_id',$vo['hotel_id'])->select();
            if (!empty($room_type)){
                foreach ($room_type as $index => $item) {
                    $room_name =  Db::name('hotel_room_type')->where('id',$item['room_type_id'])->value('room_name');
                    $room_type[$index]['room_type_name'] = (empty($room_name)) ? '房型已被删除':$room_name;
                }
            }


            // 查询所有的酒店
            $hotel = Db::name('hotel')->where('isdelete', 0)->select();
            $hotel_room_type = Db::name('hotel_room_type')->where('isdelete',0)->select();
            $this->view->assign('hotel',$hotel);
            $this->view->assign('vo',$vo);
            $this->view->assign('room_type',$room_type);
            $this->view->assign('reservationRoom',$reservationRoom);
            $this->view->assign('hotel_room_type',$hotel_room_type);
            return $this->view->fetch('edit');
        }
    }

    /**
     * 连表删除
     */
    public function delete()
    {
        $data = input();
        $delete = Db::name('hotel_reservation')->where('id',$data['id'])->delete();
        if($delete){
            Db::name('reservation_room')->where('booking_hotel_id',$data['id'])->delete();
            return ajax_return_adv('删除成功');
        }else{
            return ajax_return_adv_error('删除失败');
        }


    }

    /**
     * 获取酒店预订房型数量
     */
    public static function getReservationRoom($data)
    {
        $map = [];
        // 根据酒店id查找
        $reservation_room = Db::name('reservation_room')
                           ->where('hotel_id',$data['hotel_id'])
                           ->where('create_time',$data['create_time'])
                           ->select();

        if (!$reservation_room || !$data['id']){
            $map = [
                'room_type' => '尚未有房型',
                'number' => '尚未有数量'
            ];
            return $map;
        }
        $numberStr = '';
        foreach ($reservation_room as $index => $item) {
            $type_name = Db::name('hotel_room_type')->where('id',$item['room_type_id'])->value('room_name');
            if ($type_name) {
//                $numberStr .= "{$type_name} -- {$item['number_of_rooms']},";
                $map[] = [
                    'room_type' => $type_name,
                    'number' => $item['number_of_rooms']
                ];
            }else{
//                $numberStr .= "不存在房型 -- {$item['number_of_rooms']},";
                $map[] = [
                    'room_type' => '房型已被删',
                    'number' => $item['number_of_rooms']
                ];
            }
        }
        $numberStr = rtrim($numberStr,',');
        return $map;
    }

    /**
     * 获取酒店房型
     */
    public function getRoomType(Request $request)
    {
        $data = input();
        if (!$data['hotel_id']){
            return ajax_return_adv_error('缺少酒店的参数');
        }
        // 根据酒店的id获取房型
        $room_type = Db::name('room_hotel_number')->where('hotel_id',$data['hotel_id'])->select();
        if (!empty($room_type)){
            foreach ($room_type as $index => $item) {
                $room_name =  Db::name('hotel_room_type')->where('id',$item['room_type_id'])->value('room_name');
                $room_type[$index]['room_type_name'] = (empty($room_name)) ? '房型已被删除':$room_name;
            }
        }
        return ajax_return_adv('获取数据成功','','','','',$room_type,5);
    }

}
